/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistentie;

import domein.Episode;
import domein.Serie;
import java.io.*;
import java.util.List;
import java.util.Properties;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author vuokko
 */
public class PersistentieController {
    
    private SerieMapper serieMapper;
    private EpisodeMapper episodeMapper;
    private File xmlFile;
    
    private static PersistentieController instance;
    
    private PersistentieController() {
        serieMapper = new SerieMapper();
        episodeMapper = new EpisodeMapper();
         
        Properties p = new Properties();
        try {
            p.load(new FileInputStream("Configuration.properties"));
            xmlFile = new File(p.getProperty("xmlFile"));
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }
    }
    
    public static PersistentieController getInstance() {
        if (instance == null) { instance = new PersistentieController(); }
        return instance;
    }
    
    /**
     * 
     * @param d Document om weg te schrijven
     * @return true = savesucces, false = fail
     */
    boolean saveAllToXml(Document d) {
        boolean succes = false;
        try {
            XMLOutputter o = new XMLOutputter(Format.getPrettyFormat());
            o.output(d, new FileOutputStream(xmlFile));
            succes = true;
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            return succes;
        }
    }
    
    /**
     * 
     * @return Document representing the xml file 
     */
    Document getXMLFromFile() {
        Document d = null;
        try {
            SAXBuilder b = new SAXBuilder();
            d = b.build(xmlFile);
        } catch (JDOMException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            return d;
        }
    }

    public List<Serie> getAllSeries() {
        return serieMapper.getAllSeries();
    }

    List<Episode> getEpisodes(Element e) {
        return episodeMapper.getEpisodes(e);
    }
    
    Element getEpisodesAsElement(List<Episode> l) {
        return episodeMapper.getEpisodesAsElement(l);
    }

    public void saveAllSeries() {
        serieMapper.saveAllSeries();
    }
}
